package com.ciaj.boot.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaj.base.comm.constant.DefaultConstant;
import com.ciaj.base.comm.utils.CollectionUtil;
import com.ciaj.base.exception.BsRException;
import com.ciaj.module.sys.entity.po.SysAuth;
import com.ciaj.module.sys.entity.vo.ShiroUser;
import com.ciaj.module.sys.service.ISysAuthService;
import com.ciaj.module.sys.service.ISysUserService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * @Author: Ciaj.
 * @Date: 2018/6/4 11:13
 * @Description:
 */
@Log4j2
public class ShiroAdminRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysAuthService iSysAuthService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroUser loginUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (loginUser != null) {
            authorizationInfo.setRoles(loginUser.getJobVo().getRoles());
            authorizationInfo.setStringPermissions(loginUser.getJobVo().getPermissions());
        }
        log.debug("===========登录授权 doGetAuthorizationInfo loginUser [{}]", loginUser);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("===========登录授权 doGetAuthenticationInfo authenticationToken [{}]", authenticationToken);

        //获取用户信息
        String username = authenticationToken.getPrincipal().toString();
        ShiroUser user = iSysUserService.getShiroUserByAccount(username);
        //验证登录账号
        if (user == null) {
            throw new UnknownAccountException("用户名不存在");
        }
        if (DefaultConstant.FLAG_Y.equals(user.getLocked())) { //账户冻结
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        //
        SysAuth auth = iSysAuthService.getOne(new QueryWrapper<SysAuth>().lambda().eq(SysAuth::getUserId, user.getId()));
        if (auth == null) throw new BsRException("账号或密码不正确");

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                auth.getPassword(), //密码
                ByteSource.Util.bytes(auth.getSalt()),//salt=username+salt
                getName()  //realm name
        );
        //把登录人存进session
        SecurityUtils.getSubject().getSession().setAttribute(DefaultConstant.LOGIN_USER, user);
        return authenticationInfo;

    }

    /**
     * 清理用户权限缓存
     */
    public void clearCachedAuthorizationInfo() {
        //清空缓存
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCachedAuthorizationInfo(principals);
    }
}
